<!-- 房屋管理 -->
<template>
  <div>
    <div class="header">
      <div class="title" style="height: 65px">
        <div style="margin-bottom: 15px; width: 80%; float: left">
          <div style="width: 25%; float: left">
            <a-space direction="vertical" style="width: 100%; margin-left: 13px">
              <a-input-group compact>
                <a-cascader
                  v-model:value="strXzqdm"
                  style="width: 100%"
                  :options="XzqdmList"
                  expand-trigger="hover"
                  placeholder="请选择行政区"
                  changeOnSelect
                  @change="onChange"
                />
              </a-input-group>
            </a-space>
          </div>
          <div style="width: 8%; float: left; margin-top: 15px; margin-left: 25px">
            <a-select ref="select" v-model:value="role_type" style="width: 120px">
              <a-select-option value="4">乡镇用户</a-select-option>
              <a-select-option value="3">区级用户</a-select-option>
              <a-select-option value="2">市级用户</a-select-option>
            </a-select>
          </div>
          <div style="width: 37%; float: left; margin-top: 15px; margin-left: 10px">
            <a-space style="margin-left: 10px">
              <span>开始时间：</span>
              <a-date-picker v-model:value="startDate" :format="dateFormat" :disabledDate="disabledFutureDate"  />
            </a-space>
            <a-space style="margin-left: 10px">
              <span>结束时间：</span>
              <a-date-picker v-model:value="endDate" :format="dateFormat" :disabledDate="disabledFutureDate"  />
            </a-space>
          </div>
          <div style="float: left; width: 20%; margin-top: 15px; margin-left: 15px">
            <a-space class="search-btn">
              <a-button type="primary" style="line-height: 25px" @click="btnSeach">查询</a-button>
            </a-space>
          </div>
        </div>
        <div style="float: left; width: 20%">
          <a-space style="float: right; margin-right: 10px; margin-top: 15px">
            <a-button type="primary" @click="handleExport"> 导出全部明细 </a-button>
          </a-space>
        </div>
      </div>
      <a-table
        :dataSource="tableData"
        :columns="displayColumns"
        :pagination="false"
        :scroll="{ x: 1500, y: tableHeight }"
        bordered
        :loading="loading"
      >
        <!-- vue3 中的写法 -->
        <template #headerCell="{ column }">
          <template v-if="column.key == 'xzq'">
            <Tooltip placement="top">
              <template #title>
                <span>区县名称</span>
              </template>
              <span>区县名称 </span>
            </Tooltip>
          </template>
          <template v-if="column.key == 'town'">
            <Tooltip placement="top">
              <template #title>
                <span>乡镇名称</span>
              </template>
              <span>乡镇名称 </span>
            </Tooltip>
          </template>
          <template v-if="column.key == 'village'">
            <Tooltip placement="top">
              <template #title>
                <span>村级名称</span>
              </template>
              <span>村级名称 </span>
            </Tooltip>
          </template>
          <template v-if="column.key == 'zcount'">
            <Tooltip placement="top">
              <template #title>
                <span>房屋总数（栋）</span>
              </template>
              <span> 房屋总数（栋） </span>
            </Tooltip>
          </template>
          <template v-if="column.key == 'zccount'">
            <Tooltip placement="top">
              <template #title>
                <span>核查数量（栋）</span>
              </template>
              <span> 核查数量（栋） </span>
            </Tooltip>
          </template>
          <template v-if="column.key == 'zcl'">
            <Tooltip placement="top">
              <template #title>
                <span>核查率</span>
              </template>
              <span> 核查率 </span>
            </Tooltip>
          </template>
          <template v-if="column.key == 'yhcount'">
            <Tooltip placement="top">
              <template #title>
                <span>隐患数量（个）</span>
              </template>
              <span> 隐患数量（个） </span>
            </Tooltip>
          </template>
          <template v-if="column.key == 'zgcount'">
            <Tooltip placement="top">
              <template #title>
                <span>整改数量（个）</span>
              </template>
              <span> 整改数量（个） </span>
            </Tooltip>
          </template>
        </template>
      </a-table>
      <div class="pagination" style="float: right">
        <a-pagination
          show-size-changer
          v-model:current="pageIndex"
          v-model:pageSize="pageSize"
          :total="total"
          @show-size-change="onShowSizeChange"
        />
      </div>

      <Detail
        v-model:visible="visible"
        title="抽屉标题"
        :width="1500"
        :detailTableHeight="detailTableHeight"
        :closable="true"
        :destroyOnClose="true"
        :data="detailData"
        :detailParams="detailParams"
        :currentqx="currentqx"
        :currentTitle="currentTitle"
        @close="handleClose"
      >
        <!-- <p>抽屉内容</p> -->
      </Detail>
      <!-- <BasicTable @register="registerTable">
          <template #id="{ record }"> </template>
      </BasicTable> -->
    </div>
  </div>
</template>

<script lang="ts" setup>
import moment from 'moment';
import dayjs from 'dayjs';
import { ref, reactive, toRefs, onMounted, onBeforeMount, computed, watch } from 'vue';
import { getHcVillagePostStaticDetailList } from '/@/api/demo/system'; //统计工作进展
import { getRegion } from '/@/api/demo/api'; //统计双通道满足情况
import { useUserStore } from '/@/store/modules/user';
import { iTableData, iTableColumns } from './types/table';
import { useRouter } from 'vue-router';
import { iParams } from './types/params';
import { useGlobSetting } from '/@/hooks/setting';
import { downloadByUrl } from '/@/utils/file/download';
import Detail from './component/detailDrawer.vue';
let userInfo = ref<any>(null);
const visible = ref(false);
let detailData = ref<any[]>([]);
let detailParams = ref({}); // 详情参数
let detailTableHeight = ref<number>(0); // 表格高度
let tableHeight = ref<number>(0); // 表格高度
let pageIndex = ref(1);
let pageSize = ref(15);
let total = ref(0);
const role_type = ref<string>('4');
const router = useRouter();
const checked = ref(false);
const userStore = useUserStore();
const globSetting = useGlobSetting();
const dateFormat = 'YYYY-MM-DD';
const startDate = ref<any>(null); // 开始时间
const endDate = ref<any>(null); // 结束时间
const strXzqdm = ref<string[]>([]); //行政区
const XzqdmList = ref<string[]>([]); //行政区
const disabledFutureDate = (current) => {
  return current && current > moment().endOf('day');
};
let data = reactive<{
  tableData: iTableData[];
  tableColumns: iTableColumns[];
  wscolsList: { wch: number }[];
  id: number | any;
  loading: Boolean;
  keyWorld: String;
  currentqx: string; // 当前行政区名称
  currentTitle: string;
  cityToken: string | any;
  pageIndex: number;
  pageSize: number;
  total: number;
  startTime: string;
  endTime: string;
}>({
  // 表格数据
  tableData: [],
  tableColumns: [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      align: 'center',
      width: 100,
    },
    {
      title: '区县名称',
      dataIndex: 'xzq',
      key: 'xzq',
      align: 'center',
      width: 100,
    },
    {
      title: '乡镇名称',
      dataIndex: 'town',
      key: 'town',
      align: 'center',
      width: 130,
    },
    {
      title: '村级名称',
      dataIndex: 'village',
      key: 'village',
      align: 'center',
      width: 210,
    },
    {
      title: '房屋总数(栋)',
      dataIndex: 'zcount',
      key: 'zcount',
      align: 'center',
      width: 170,
    },
    {
      title: '核查数量（栋）',
      dataIndex: 'hccount',
      key: 'jccount',
      align: 'center',
      width: 170,
      customCell: (row, index, column) => {
        let isNoHzyh = row.xzq !== '汇总' ? true : false;
        let style = 'cursor:pointer;text-decoration: underline; color: blue;';
        let isNoZero = row[column.key] !== 0 ? true : false;
        return {
          style: `${isNoHzyh === true && isNoZero ? style : ''}`,
          class: 'cell-hover',
          onClick: async () => {
            getDetailData(row, index, column, isNoHzyh, isNoZero);
          },
        };
      },
    },
    {
      title: '未核查数量（栋）',
      dataIndex: 'whccount',
      key: 'whccount',
      align: 'center',
      width: 170,
      customCell: (row, index, column) => {
        let isNoHzyh = row.xzq !== '汇总' ? true : false;
        let style = 'cursor:pointer;text-decoration: underline; color: blue;';
        let isNoZero = row[column.key] !== 0 ? true : false;
        return {
          style: `${isNoHzyh === true && isNoZero ? style : ''}`,
          class: 'cell-hover',
          onClick: async () => {
            pageIndex.value = 1;
            pageSize.value = 15;
            getWzcDetailData(row, index, column, isNoHzyh, isNoZero);
          },
        };
      },
    },
    {
      title: '核查率',
      dataIndex: 'hcl',
      key: 'hcl',
      align: 'center',
      width: 130,
    },

    {
      title: '已达标数量（栋）',
      dataIndex: 'ydbcount',
      key: 'ydbcount',
      align: 'center',
      width: 170,
      // customCell: (row, index, column) => {
      //   let isNoHzyh = row.xzq !== '汇总' ? true : false;
      //   let style = 'cursor:pointer;text-decoration: underline; color: blue;';
      //   let isNoZero = row[column.key] !== 0 ? true : false;
      //   return {
      //     style: `${isNoHzyh === true && isNoZero ? style : ''}`,
      //     class: 'cell-hover',
      //     onClick: async () => {
      // getYdbDetailData(row, index, column, isNoHzyh, isNoZero);
      //     },
      //   };
      // },
    },
    {
      title: '未达标数量（栋）',
      dataIndex: 'wdbcount',
      key: 'wdbcount',
      align: 'center',
      width: 170,
      // customCell: (row, index, column) => {
      //   let isNoHzyh = row.xzq !== '汇总' ? true : false;
      //   let style = 'cursor:pointer;text-decoration: underline; color: blue;';
      //   let isNoZero = row[column.key] !== 0 ? true : false;
      //   return {
      //     style: `${isNoHzyh === true && isNoZero ? style : ''}`,
      //     class: 'cell-hover',
      //     onClick: async () => {
      // pageIndex.value=1;
      // pageSize.value=15;
      // getWdbDetailData(row, index, column, isNoHzyh, isNoZero);
      //     },
      //   };
      // },
    },
    {
      title: '达标率',
      dataIndex: 'dbl',
      key: 'dbl',
      align: 'center',
      width: 130,
    },

    {
      title: '隐患数量（个）',
      dataIndex: 'yhcount',
      key: 'yhcount',
      align: 'center',
      width: 170,
      // customCell: (row, index, column) => {
      //   let isNoHzyh = row.xzq !== '汇总' ? true : false;
      //   let style = 'cursor:pointer;text-decoration: underline; color: blue;';
      //   let isNoZero = row[column.key] !== 0 ? true : false;
      //   return {
      //     style: `${isNoHzyh === true && isNoZero ? style : ''}`,
      //     class: 'cell-hover',
      //     onClick: async () => {
      //       getYhDetailData(row, index, column, isNoHzyh, isNoZero);
      //     },
      //   };
      // },
    },
    {
      title: '整改数量（个）',
      dataIndex: 'zgcount',
      key: 'zgcount',
      align: 'center',
      width: 170,
      // customCell: (row, index, column) => {
      //   let isNoHzyh = row.xzq !== '汇总' ? true : false;
      //   let style = 'cursor:pointer;text-decoration: underline; color: blue;';
      //   let isNoZero = row[column.key] !== 0 ? true : false;
      //   return {
      //     style: `${isNoHzyh === true && isNoZero ? style : ''}`,
      //     class: 'cell-hover',
      //     onClick: async () => {
      //       getZgDetailData(row, index, column, isNoHzyh, isNoZero);
      //     },
      //   };
      // },
    },
    {
      title: '剩余隐患数量（个）',
      dataIndex: 'syyhcount',
      key: 'syyhcount',
      align: 'center',
      width: 170,
      // customCell: (row, index, column) => {
      //   let isNoHzyh = row.xzq !== '汇总' ? true : false;
      //   let style = 'cursor:pointer;text-decoration: underline; color: blue;';
      //   let isNoZero = row[column.key] !== 0 ? true : false;
      //   return {
      //     style: `${isNoHzyh === true && isNoZero ? style : ''}`,
      //     class: 'cell-hover',
      //     onClick: async () => {
      //       getSyDetailData(row, index, column, isNoHzyh, isNoZero);
      //     },
      //   };
      // },
    },
  ],
  id: null,
  loading: true,
  keyWorld: '',
  cityToken: '', // 判断是不是市区 110000 是北京市 展示搜索宽
  currentqx: '', // 当前行政区名称
  currentTitle: '', // 当前详情标题
  total: 0,
  wscolsList: [{ wch: 15 }, { wch: 15 }, { wch: 15 }, { wch: 15 }, { wch: 15 }, { wch: 15 }],
});
// 表格的 ref Dom名称
let { tableData, loading, currentqx, currentTitle } = toRefs(data);
async function getData() {
  if (startDate.value == null) {
    let currentDate = moment().format('YYYY-MM-DD');
    const start: any = dayjs(currentDate);
    const end: any = dayjs(currentDate);
    startDate.value = start;
    endDate.value = end;
    getTime();
  }

  const { role } = userInfo.value;
  let groupname = '';
  if (role === 'City') {
    groupname = 'qxmc';
  } else if (role === 'Area') {
    groupname = 'jzmc';
  } else if (role === 'Street') {
    groupname = 'czmc';
  }
  console.log('*****************value18*****************', value18);
  let params: iParams = {
    groupname: groupname,
    pageIndex: pageIndex.value,
    pageSize: pageSize.value,
    startTime: moment(startDate.value.$d).format('YYYY-MM-DD'),
    endTime: moment(endDate.value.$d).format('YYYY-MM-DD'),
    cked: checked.value,
    roletype: role_type.value,
  };
  if (strXzqdm.value != undefined) {
    params.xzqdm = strXzqdm.value[0];
    params.towndm = strXzqdm.value[1];
    params.villagedm = strXzqdm.value[2];
  }

  // console.log('@市级参数', params);
  loading.value = true;
  let res: any = await getHcVillagePostStaticDetailList(params);
  console.log('@res--工作进入汇总表', res);

  if (res || res.items.length > 0) {
    loading.value = false;
    data.tableData = [...res.items];
    total.value = res.total;
  }
}

//已核查数量
const getDetailData = async (row: any) => {
  router.push({
    path: 'hcDetail/hchourselist',
    query: {
      xzqdm: row.xzqdm,
      towndm: row.towndm,
      villagedm: row.villagedm,
      category: 'yhy',
      yhly: role_type.value,
      currentTitle: row.xzq + '【已核查明细】明细',
      startTime: moment(startDate.value.$d).format('YYYY-MM-DD'),
      endTime: moment(endDate.value.$d).format('YYYY-MM-DD'),
    },
  });
};

//未核查数量
const getWzcDetailData = async (row: any) => {
  router.push({
    path: 'hcDetail/hchourselist',
    query: {
      xzq: row.xzq,
      xzqdm: row.xzqdm,
      towndm: row.towndm,
      villagedm: row.villagedm,
      cked: checked.value + '',
      yhly: role_type.value + '',
      floor: '2',
      category: 'wzc',
      currentTitle: row.xzq + '【未核查明细】明细',
      startTime: moment(startDate.value.$d).format('YYYY-MM-DD'),
      endTime: moment(endDate.value.$d).format('YYYY-MM-DD'),
    },
  });
};
//已达标的房屋
const getYdbDetailData = async (
  row: any,
  index: number,
  column: any,
  isNoHzyh: boolean,
  isNoZero: boolean,
) => {
  if (isNoHzyh && isNoZero) {
    console.log('已达标的房屋明细');
    let params = {
      groupbyLever_code: row.xzqdm,
      groupbyLever_code_project: column.key,
      xzqdm: row.xzqdm,
      towndm: row.towndm,
      villagedm: row.villagedm,
      category: '6',
      yhly: role_type.value,
      titlename: '已达标的房屋明细',
      startTime: moment(startDate.value.$d).format('YYYY-MM-DD'),
      endTime: moment(endDate.value.$d).format('YYYY-MM-DD'),
    };
    detailParams.value = params;
    data.currentTitle = row.xzq + '-' + row.town + '-' + row.village;
    showDrawer();
  }
};
//未达标的房屋
const getWdbDetailData = async (
  row: any,
  index: number,
  column: any,
  isNoHzyh: boolean,
  isNoZero: boolean,
) => {
  if (isNoHzyh && isNoZero) {
    console.log('未达标的房屋明细');
    let params = {
      groupbyLever_code: row.xzqdm,
      groupbyLever_code_project: column.key,
      xzqdm: row.xzqdm,
      towndm: row.towndm,
      villagedm: row.villagedm,
      category: '7',
      yhly: role_type.value,
      titlename: '未达标的房屋明细',
      startTime: moment(startDate.value.$d).format('YYYY-MM-DD'),
      endTime: moment(endDate.value.$d).format('YYYY-MM-DD'),
      };
      detailParams.value = params;
      data.currentTitle = row.xzq + '-' + row.town + '-' + row.village;
      showDrawer();
    }
  };
  //获取隐患情况
  const getYhDetailData = async (
    row: any,
    index: number,
    column: any,
    isNoHzyh: boolean,
    isNoZero: boolean,
  ) => {
    if (isNoHzyh && isNoZero) {
      let params = {
        groupbyLever_code: row.xzqdm,
        groupbyLever_code_project: column.key,
        xzqdm: row.xzqdm,
        towndm: row.towndm,
        villagedm: row.villagedm,
        category: '3',yhly:role_type.value,
        titlename: '房屋隐患明细',
		startTime: moment(startDate.value.$d).format('YYYY-MM-DD'),
        endTime: moment(endDate.value.$d).format('YYYY-MM-DD'),
      };
      detailParams.value = params;
      data.currentTitle = row.xzq + '-' + row.town + '-' + row.village;
      showDrawer();
    }
  };
  //获取整改情况
  const getZgDetailData = async (
    row: any,
    index: number,
    column: any,
    isNoHzyh: boolean,
    isNoZero: boolean,
  ) => {
    if (isNoHzyh && isNoZero) {
      let params= {
        groupbyLever_code: row.xzqdm,
        groupbyLever_code_project: column.key,
        xzqdm: row.xzqdm,
        towndm: row.towndm,
        villagedm: row.villagedm,
        category: '4',yhly:role_type.value,
        titlename: '房屋整改明细',
		startTime: moment(startDate.value.$d).format('YYYY-MM-DD'),
        endTime: moment(endDate.value.$d).format('YYYY-MM-DD'),
      };
      detailParams.value = params;
      data.currentTitle = row.xzq + '-' + row.town + '-' + row.village;
      showDrawer();
    }
  };
  //获取剩余隐患情况
  const getSyDetailData = async (
    row: any,
    index: number,
    column: any,
    isNoHzyh: boolean,
    isNoZero: boolean,
  ) => {
    if (isNoHzyh && isNoZero) {
      let params = {
        groupbyLever_code: row.xzqdm,
        groupbyLever_code_project: column.key,
        xzqdm: row.xzqdm,
        towndm: row.towndm,
        villagedm: row.villagedm,
        category: '5',
        yhly: role_type.value,
        titlename: '剩余房屋隐患明细',
		startTime: moment(startDate.value.$d).format('YYYY-MM-DD'),
        endTime: moment(endDate.value.$d).format('YYYY-MM-DD'),
		
      };
      detailParams.value = params;
      data.currentTitle = row.xzq + '-' + row.town + '-' + row.village;
      showDrawer();
    }
  };
  
  // 切换页码的时候更新  pageIndex 和  pageSize
  const onShowSizeChange = (pageIndex: number, pageSize: number) => {
    // antDesign  自动给  pageIndex 和 pageSize 赋值
    // pageIndex.value = pageIndex;
    // pageSize.value = pageSize;
    // console.log('@pageIndex,pageSize', pageIndex, pageSize);
  };
  function handleExport() {
	
    const uriBase = `${globSetting.apiBaseUrl}${globSetting.apiUrl}`;
    const tk = userStore.getToken;
    getTime();
	let xzqdm="";
	let towndm="";
	let villagedm="";
	if(value18.value[0]!=undefined)
	{
		xzqdm=value18.value[0];
	}
	if(value18.value[1]!=undefined)
	{
		towndm=value18.value[1];
	}
	if(value18.value[2]!=undefined)
	{
		villagedm=value18.value[2];
	}
const arr = strXzqdm.value || [];
 xzqdm = arr[0] || '';
 towndm = arr[1] || '';
 villagedm = arr[2] || '';
    downloadByUrl({
      url:
        uriBase +
        '/hc/evolvestatic/ExportDetailedExcel?access_token=' +
        tk +
        '&startTime=' +
        startDate.value.format('YYYY-MM-DD') +
        '&endTime=' +
        endDate.value.format('YYYY-MM-DD') +
		'&roletype=' +
        role_type.value +
		'&xzqdm=' +
	xzqdm+
        '&towndm=' +
     towndm+
        '&villagedm=' + villagedm ,
      target: '_blank',
    });
  }
 async function getRegionData() {
    let res: any = await getRegion();
    XzqdmList.value = res;
  }
  function getTime() {
    data.startTime = moment(startDate.value.$d).format('YYYY-MM-DD');
    data.endTime = moment(endDate.value.$d).format('YYYY-MM-DD');
    console.log('@查询参数 -- 开始时间', data.startTime);
    console.log('@查询参数 -- 结束时间', data.endTime);
  }
  function btnSeach() {
    getData();
  }
  // 打开抽屉
  function showDrawer() {
    visible.value = true;
  }
  function handleClose() {
    visible.value = false;
  }
  function getUserInfo() {
    const userStore = useUserStore();
    userInfo.value = userStore?.getUserInfo;
  }
  const displayColumns = computed(() => {
    const { role } = userInfo.value;
    let arr: any[] = [];
    if (role === 'City') {
      // qx
      arr = data.tableColumns.filter((item) => item.key !== 'jzmc' && item.key !== 'czmc');
      return arr;
    } else if (role === 'Area') {
      // jz
      arr = data.tableColumns.filter((item) => item.key !== 'czmc' && item.key !== 'qxmc');
      return arr;
    } else if (role === 'Street') {
      // cun
      arr = data.tableColumns.filter((item) => item.key !== 'jzmc' && item.key !== 'qxmc');
      console.log('@Aarr', arr);
      return arr;
    } else {
      return data.tableColumns;
    }
  });
  const getTableHeight = () => {
    setTimeout(() => {
      // detailTableHeight.value = window.innerHeight - 182;
      // tableHeight.value = window.innerHeight - 292;
      detailTableHeight.value = window.innerHeight;
      tableHeight.value = window.innerHeight;
      // console.log(`表格高度`, tableHeight.value);
    });
  };

const value18 = ref<string[]>([]);
watch(pageSize, () => {
  console.log('pageSize', pageSize.value);
  getData();
});
watch(pageIndex, () => {
  console.log('current', pageIndex.value);
  getData();
});
onBeforeMount(() => {
  getUserInfo();
});
onMounted(() => {
  console.log('******工作进展统计初始化******');
  getRegionData();
  getData();
  getTableHeight();
});
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">
#map {
  height: calc(100vh - 140px);
}

.x-houseMng-search {
  z-index: 100;
  margin: 6px;
  position: absolute;
}

.root-house-mng-main {
  margin: 6px;
}

.x-village-tabs {
  //z-index: 100;
  //position: absolute;
  width: 60vw;
  margin-top: 6px;
  margin-left: 40px;
  //background-color: rgba(34, 34, 34, 0.6);
  :deep(.ant-form) {
    margin-top: 6px;
  }

  // :deep(.ant-form-item-label) > label {
  //   color: white;
  // }
}
.site-input-group-wrapper .site-input-split {
  background-color: #fff;
}

.site-input-group-wrapper .site-input-right {
  border-left-width: 0;
}

.site-input-group-wrapper .site-input-right:hover,
.site-input-group-wrapper .site-input-right:focus {
  border-left-width: 1px;
}

.site-input-group-wrapper .ant-input-rtl.site-input-right {
  border-right-width: 0;
}

.site-input-group-wrapper .ant-input-rtl.site-input-right:hover,
.site-input-group-wrapper .ant-input-rtl.site-input-right:focus {
  border-right-width: 1px;
}
[data-theme='dark'] .site-input-group-wrapper .site-input-split {
  background-color: transparent;
}
</style>
